package com.hfjyz.registration.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import org.springframework.web.servlet.view.RedirectView;

import com.hfjyz.registration.command.UserPasswordResetCommand;
import com.hfjyz.registration.contants.ExamContants;
import com.hfjyz.registration.model.Exam;
import com.hfjyz.registration.service.UserPasswordService;

public class UserPasswordResetController extends SimpleFormController {
	private UserPasswordService userPasswordService;
	private String initPassword = null;

	public UserPasswordService getUserPasswordService() {
		return userPasswordService;
	}

	public void setUserPasswordService(UserPasswordService userPasswordService) {
		this.userPasswordService = userPasswordService;
	}

	public String getInitPassword() {
		return initPassword;
	}

	public void setInitPassword(String initPassword) {
		this.initPassword = initPassword;
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		UserPasswordResetCommand cmd = (UserPasswordResetCommand) command;
		Exam exam = (Exam) request.getSession().getAttribute(
				ExamContants.SESSION_KEY_EXAM_INFO);
		String submitType = cmd.getSubmitType();
		if ("reset".equals(submitType)) {
			userPasswordService.searchUserApplyInfo(cmd, exam.getId(), errors);
			Map model = errors.getModel();
			if (!errors.hasErrors()) {
				userPasswordService.resetUserPasswor(cmd.getIdCardNo(),
						initPassword, exam.getId());
				model.put("alert", true);
			}
			return new ModelAndView(getFormView(), model);
		} else {
			return new ModelAndView(new RedirectView("adminInit.action"));
		}
	}
}
